package com.atguigu.gmall.order.controller;

import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.cart.client.CartFeignClient;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import com.atguigu.gmall.model.order.OrderDetail;
import com.atguigu.gmall.model.order.OrderInfo;
import com.atguigu.gmall.model.user.UserAddress;
import com.atguigu.gmall.order.service.OrderInfoService;
import com.atguigu.gmall.product.client.ProductFeignClient;
import com.atguigu.gmall.user.client.UserFeignClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/order")
public class OrderApiController {
    @Autowired
    private UserFeignClient userFeignClient;
    @Autowired
    private CartFeignClient cartFeignClient;
    @Autowired
    private ProductFeignClient productFeignClient;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private OrderInfoService orderInfoService;

    @GetMapping("/trade")
    public Map<String,Object> trade(HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);

        Map<String,Object> result = new HashMap();
        //1、获取用户收货地址
        List<UserAddress> userAddressList = userFeignClient.getUserInfoAddress();
        result.put("userAddressList",userAddressList);

        //2、获取选中商品清单
        List<CartInfo> cartInfoList = cartFeignClient.checkedCartInfoList();
        //订单详情集合 -->偷天换日
        List<OrderDetail> detailArrayList = cartInfoList.stream().map(cartInfo -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setSkuId(cartInfo.getSkuId());
            orderDetail.setImgUrl(cartInfo.getImgUrl());
            orderDetail.setSkuName(cartInfo.getSkuName());
            orderDetail.setSkuNum(cartInfo.getSkuNum());
            BigDecimal price = productFeignClient.getPrice(cartInfo.getSkuId());
            orderDetail.setOrderPrice(price);
            return orderDetail;
        }).collect(Collectors.toList());
        result.put("detailArrayList",detailArrayList);

        //3、交易号 防止幂等性问题
        String tradeNo = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set("tradeNo" + userId,tradeNo);
        result.put("tradeNo",tradeNo);
        //4、小计之总件数
        long totalNum = detailArrayList.stream().collect(Collectors.
                summarizingLong(OrderDetail::getSkuNum)).getSum();
        result.put("totalNum",totalNum);
        //5、小计之总金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderDetail orderDetail : detailArrayList) {
             totalAmount = totalAmount.add(orderDetail.getOrderPrice()
                    .multiply(new BigDecimal(orderDetail.getSkuNum())));
        }
        result.put("totalAmount",totalAmount);

        return result;
    }

    //提交订单
    @PostMapping("/auth/submitOrder")
    public Result submitOrder(String tradeNo, @RequestBody OrderInfo orderInfo,
                              HttpServletRequest request){
        String userId = AuthContextHolder.getUserId(request);
        //1、校验交易号
        String tradeNo1 = (String) redisTemplate.opsForValue().get("tradeNo" + userId);
        if (null != tradeNo1){
            if (StringUtils.isEmpty(tradeNo)){
                return Result.fail().message("操作不当");
            }else {
                if (!tradeNo.equals(tradeNo1)){
                    return Result.fail().message("请勿重新提交订单");
                }else {
                    redisTemplate.delete("tradeNo" + userId);
                }
            }
        }else {
            return Result.fail().message("请勿重新提交订单");
        }
        //删除交易号
        redisTemplate.delete("tradeNo" + userId);

        //2、校验库存  连接库存管理系统
        List<OrderDetail> orderDetailList = orderInfo.getOrderDetailList();
        for (OrderDetail orderDetail : orderDetailList) {
            boolean flag = orderInfoService.hasStock(orderDetail.getSkuId(),orderDetail.getSkuNum());
            if (!flag){
                return Result.fail().message(orderDetail.getSkuName() + "|无货");
            }
        }
        //3、保存订单
        orderInfo.setUserId(Long.parseLong(userId));
        Long orderId = orderInfoService.saveOrder(orderInfo);

        return Result.ok(orderId);
    }

    //查询订单信息
    @GetMapping("/getOrderInfo/{orderId}")
    public OrderInfo getOrderInfo(@PathVariable Long orderId){

        return orderInfoService.getOrderInfo(orderId);
    }

    //接收库存系统发起的 拆单请求
    @PostMapping("/orderSpilt")
    public String orderSpilt(@PathVariable Long orderId,@PathVariable String wareSkuMap){
        //1、拆单
        List<OrderInfo> orderInfoList = orderInfoService.orderSpilt(orderId,wareSkuMap);

        //2、响应值 返回值 List<Map>
        List<Map> listMap = orderInfoList.stream().map(orderInfo ->
                orderInfoService.initWareOrder(orderInfo)
        ).collect(Collectors.toList());

        //转换
        return JSONObject.toJSONString(listMap);

    }

}
